package adger.me.yili.view.impl;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import net.soulwolf.widget.speedyselector.widget.SelectorEditText;
import net.soulwolf.widget.speedyselector.widget.SelectorTextView;

import org.xutils.DbManager;
import org.xutils.db.table.DbModel;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;

import adger.me.yili.R;
import adger.me.yili.activity.OrderDetailMActivity;
import adger.me.yili.bean.CrashInfoBean;
import adger.me.yili.bean.OrderUpdataUpBean;
import adger.me.yili.bean.OrdersBeanTable;
import adger.me.yili.bean.QueryHistoryGroupBean;
import adger.me.yili.bean.Token;
import adger.me.yili.utils.DB;
import adger.me.yili.utils.SharePreferencesUtil;
import adger.me.yili.utils.UriCenter;
import adger.me.yili.utils.XHttp;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {


    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.stv_currentVersion)
    SelectorTextView stv_currentVersion;
    @Bind(R.id.set_input_vipNumber)
    SelectorEditText set_input_vipNumber;
    @Bind(R.id.set_input_phone)
    SelectorEditText set_input_phone;
    @Bind(R.id.ll_menu_left)
    LinearLayout ll_menu_left;
    DbManager dbManager;
    public static MainActivity mInstance = null;
    @Bind(R.id.tv_menu_rightTitle)
    TextView tv_menu_rightTitle;
    @Bind(R.id.tv_claim_day)
    TextView tv_claim_day;
    @Bind(R.id.actv_input_userName)
    AutoCompleteTextView actv_input_userName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mInstance = this;
        title.setText(SharePreferencesUtil.getSpString("activityTitle", "服务点", this));
        dbManager = DB.getXInstance();
        tv_menu_rightTitle.setText("更新");
        tv_menu_rightTitle.setBackgroundColor(Color.parseColor("#E57918"));
        upCrashInfo();
        if (SharePreferencesUtil.getSpBoolean("isFirstEnter", true, MainActivity.this)) {
            update();
        } else {
            stv_currentVersion.setText(SharePreferencesUtil.getSpString("curryGroup_no", "", MainActivity.this));
            tv_claim_day.setText(SharePreferencesUtil.getSpString("claim_day", "", MainActivity.this));
        }
//        String str = "你好世界";
//        String fullresult = PinyinHelper.convertToPinyinString(str, ",", PinyinFormat.WITHOUT_TONE); // ni,hao,shi,jie
//        String result = PinyinHelper.getShortPinyin(str); // nhsj
//        Logger.d(fullresult + "   ---   " + result);
        getAllUserName();
//

    }

    private void upCrashInfo() {
        if (!TextUtils.isEmpty(SharePreferencesUtil.getSpString("crashInfo", "", this))) {
            CrashInfoBean crashInfoBean = new CrashInfoBean();
            crashInfoBean.setInfo(SharePreferencesUtil.getSpString("crashInfo", "", this));
            crashInfoBean.save(this);
            SharePreferencesUtil.putSpString("crashInfo", "", this);//置空
        }
    }

    public void update() {
        Logger.d(" update  CLICK");
        OrderUpdataUpBean upBean = new OrderUpdataUpBean();
        upBean.setToken(SharePreferencesUtil.getSpString("histryToken", "", this));
        upBean.setGroup_id(0);
        upBean.setForce(1);
        XHttp.post(UriCenter.orders, upBean, new XHttp.XCallback<OrdersBeanTable>() {

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                Logger.d(ex.getLocalizedMessage());
                Logger.d(ex.getMessage());
                Toast.makeText(MainActivity.this, "没有查询到数据", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(OrdersBeanTable bean) {
                if (analyzeData(bean)) {
                    SharePreferencesUtil.putSpBoolean("isFirstEnter", false, MainActivity.this);
                }
            }
        });
    }

    private Boolean analyzeData(OrdersBeanTable bean) {
        if (bean == null) {
            Toast.makeText(this, "成功接受,但数据为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        Logger.d(" update  onSuccess start");
        SharePreferencesUtil.putSpString("curryGroup_no", bean.getGroup_no() + "", MainActivity.this);
        SharePreferencesUtil.putSpString("claim_day", bean.getClaim_day() + "", MainActivity.this);
        stv_currentVersion.setText(bean.getGroup_no() + "");
        tv_claim_day.setText(bean.getClaim_day());
        String OrdersBeanjson = new Gson().toJson(bean);
        OrdersBeanTable ordersBeanTable = new Gson().fromJson(OrdersBeanjson, OrdersBeanTable.class);
        try {
            ArrayList<String> numList = new ArrayList<String>();
            ArrayList<OrdersBeanTable.OrdersEntity.OrderLinesEntity> OrderLinesEntityList = new ArrayList<OrdersBeanTable.OrdersEntity.OrderLinesEntity>();
            for (OrdersBeanTable.OrdersEntity ordersEntity : ordersBeanTable.getOrders()) {
                ordersEntity.setPartent_id(ordersBeanTable.getGroup_id());
                numList.add(ordersEntity.getId());
                for (OrdersBeanTable.OrdersEntity.OrderLinesEntity orderLinesEntity : ordersEntity.getOrder_lines()) {
                    orderLinesEntity.setPartent_id(ordersEntity.getId());
                    OrderLinesEntityList.add(orderLinesEntity);
                }
            }
            dbManager.delete(OrdersBeanTable.class);
            dbManager.delete(OrdersBeanTable.OrdersEntity.class);
            dbManager.delete(OrdersBeanTable.OrdersEntity.OrderLinesEntity.class);
            dbManager.save(ordersBeanTable);//第一层
            dbManager.save(ordersBeanTable.getOrders());//批量操作 第二层
            dbManager.save(OrderLinesEntityList);//批量操作 第三层
            OrdersBeanTable.OrdersEntity ordersEntity = dbManager.selector(OrdersBeanTable.OrdersEntity.class).where("partent_id", "=", bean.getGroup_id()).findFirst();
//            Logger.d("update  完成   注意条件  现在是写死的  " + ordersEntity.getId());
//            Toast.makeText(MainActivity.this, "网络数据加载完成", Toast.LENGTH_SHORT).show();
            getAllUserName();
            return true;
        } catch (DbException e) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "数据加载失败", Toast.LENGTH_SHORT).show();
            Logger.d("------异常-------");
            return false;
        }
    }

    @OnClick({R.id.tv_menu_rightTitle, R.id.stv_query, R.id.sll_curryTotal, R.id.sll_historyQuery, R.id.ll_menu_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_menu_rightTitle:
                Toast.makeText(this, "更新中....", Toast.LENGTH_SHORT).show();
                update();
                break;
            case R.id.stv_query:
                if (SharePreferencesUtil.getSpBoolean("isFirstEnter", true, MainActivity.this)) {
                    Toast.makeText(this, "数据加载中,如果长时间未响应,手动点击更新", Toast.LENGTH_SHORT).show();
                    return;
                }
                String vipNumber = set_input_vipNumber.getText().toString();
                String inputPhone = set_input_phone.getText().toString();
                String userName = actv_input_userName.getText().toString();
                if (!TextUtils.isEmpty(vipNumber)) {//vipNumber 有值
                    queryByEdit("user_sn", vipNumber);//TODO 一定要加载完了才能调用 还没做处理
                } else if (!TextUtils.isEmpty(inputPhone)) {//如果 inputPhoney 有值
                    queryByEdit("telephone", inputPhone);//TODO 一定要加载完了才能调用 还没做处理
                } else if (!TextUtils.isEmpty(userName)) {//如果 inputPhoney 有值
                    queryByEdit("user", userName);//TODO 一定要加载完了才能调用 还没做处理
                }

                break;
            case R.id.sll_curryTotal:
                if (SharePreferencesUtil.getSpBoolean("isFirstEnter", true, MainActivity.this)) {
                    Toast.makeText(this, "数据加载中,如果长时间未响应,手动点击更新", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(new Intent(this, OrderActivity.class));
                break;
            case R.id.sll_historyQuery:
                onCreateDialog().show();
                break;
            case R.id.ll_menu_left:
                DbManager dbManager = DB.getXInstance();
                try {
                    dbManager.delete(Token.class);
                } catch (DbException e) {
                    e.printStackTrace();
                }
                startActivity(new Intent(this, LoginActivity.class));
                finish();
                break;
        }
    }

    private void queryHistoryGroup(String s) {
        QueryHistoryGroupBean queryBean = new QueryHistoryGroupBean();
        queryBean.setToken(SharePreferencesUtil.getSpString("histryToken", "", this));
        queryBean.setGroup_no(Integer.parseInt(s));
        XHttp.post(UriCenter.group_orders, queryBean, new XHttp.XCallback<OrdersBeanTable>() {

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(MainActivity.this, "没有查询到数据", Toast.LENGTH_SHORT).show();
                ex.printStackTrace();
            }

            @Override
            public void onSuccess(OrdersBeanTable bean) {
                analyzeData(bean);
            }
        });
    }

    public Dialog onCreateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // Get the layout inflater
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_queryhistory, null);
        final EditText editText = (EditText) view.findViewById(R.id.et_history);
        builder.setView(view)
                .setPositiveButton("查询", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        if (!TextUtils.isEmpty(editText.getText().toString().trim())) {
                            queryHistoryGroup(editText.getText().toString().trim());
                        }
                    }
                });

        return builder.create();
    }

    private void queryByEdit(String whereName, String whereValue) {
        try {
            OrdersBeanTable.OrdersEntity ordersEntity = dbManager.selector(OrdersBeanTable.OrdersEntity.class).where(whereName, "=", whereValue).findFirst();
            if (ordersEntity == null) {
                Toast.makeText(this, "未查询到数据", Toast.LENGTH_SHORT).show();
                return;
            }
            String ordersEntityStr = new Gson().toJson(ordersEntity);
            Logger.d("注意条件 现在写死的    " + ordersEntityStr);
            Intent intent = new Intent(this, OrderDetailMActivity.class);
            intent.putExtra("ordersEntityStr", ordersEntityStr);
            startActivity(intent);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    private void getAllUserName() {
        try {
            ArrayList<String> stringArrayList = new ArrayList<String>();
            List<DbModel> dbModels = dbManager.selector(OrdersBeanTable.OrdersEntity.class).select("user").findAll();
            if (dbModels == null || dbModels.size() == 0) {
                return;
            }
            for (DbModel entity : dbModels) {
                stringArrayList.add(entity.getString("user"));
            }
            //new ArrayAdapter对象并将autoStr字符串数组传入actv中
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    R.layout.pop_item, stringArrayList);
            actv_input_userName.setAdapter(adapter);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
}
